package config

import (
	"context"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"log"
)

var Db *mongo.Database

func init() {
	dsn := "mongodb://localhost:27017"
	client, err := mongo.Connect(options.Client().ApplyURI(dsn).SetBSONOptions(&options.BSONOptions{
		UseJSONStructTags: true, // 可选
	}))
	if err != nil {
		panic(err)
	}
	Db = client.Database(Cfg.Database.Mongodb.Database)

	//创建users索引
	indexUser := mongo.IndexModel{
		Keys:    bson.D{{Key: "username", Value: 1}},
		Options: options.Index().SetUnique(true),
	}
	_, err = Db.Collection("users").Indexes().CreateOne(context.TODO(), indexUser)
	if err != nil {
		log.Fatal(err)
	}

	//创建admins索引
	indexAdmin := mongo.IndexModel{
		Keys:    bson.D{{Key: "username", Value: 1}},
		Options: options.Index().SetUnique(true),
	}
	_, err = Db.Collection("admins").Indexes().CreateOne(context.TODO(), indexAdmin)
	if err != nil {
		log.Fatal(err)
	}
}
